package com.atguigu.gmall.list.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.list.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Fxz
 * @version 1.0
 * @date 2022-02-20 20:33
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ListReceiver {

	private final SearchService searchService;

	/**
	 * 监听上架消息
	 */
	@SneakyThrows
	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(value = MqConst.QUEUE_GOODS_UPPER, durable = "true", autoDelete = "false"),
			exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS), key = { MqConst.ROUTING_GOODS_UPPER }))
	public void upperGoods(Long skuId, Message message, Channel channel) {
		if (skuId != null) {
			searchService.upperGoods(skuId);
			log.info("商品上架:{}", skuId);
		}
		// 消息确认
		try {
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		}
		catch (IOException e) {
			e.printStackTrace();
			log.error("商品上架失败:{}", e.getMessage());
			channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
		}
	}

	/**
	 * 监听下架消息
	 */
	@SneakyThrows
	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(value = MqConst.QUEUE_GOODS_LOWER, durable = "true", autoDelete = "false"),
			exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS), key = { MqConst.ROUTING_GOODS_LOWER }))
	public void lowerGoods(Long skuId, Message message, Channel channel) {
		if (skuId != null) {
			searchService.lowerGoods(skuId);
			log.info("商品下架:{}", skuId);
		}
		// 消息确认
		try {
			channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		}
		catch (IOException e) {
			e.printStackTrace();
			log.error("商品下架失败:{}", e.getMessage());
			channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
		}
	}

}
